package es.udc.emarketapp.emarket.model.usersFacade.actions;

import es.udc.emarketapp.emarket.model.client.dao.SQLClientDAO;
import es.udc.emarketapp.emarket.model.client.dao.SQLClientDAOFactory;
import es.udc.emarketapp.emarket.model.client.vo.ClientVO;
import es.udc.emarketapp.emarket.model.seller.dao.SQLSellerDAO;
import es.udc.emarketapp.emarket.model.seller.dao.SQLSellerDAOFactory;
import es.udc.emarketapp.emarket.model.seller.vo.SellerVO;
import es.udc.emarketapp.emarket.util.exceptions.model.NifCifAlreadyExistsException;
import es.udc.emarketapp.emarket.util.exceptions.model.UserNameAlreadyExistsException;
import java.sql.Connection;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.exceptions.ModelException;
import es.udc.fbellas.j2ee.util.sql.TransactionalPlainAction;

public class CreateSellerAction implements TransactionalPlainAction {

    private SellerVO sellerVO;

    public CreateSellerAction(SellerVO sellerVO) {
        this.sellerVO = sellerVO;
    }

    public Object execute(Connection connection)
            throws InternalErrorException, ModelException {

        SQLSellerDAO sellerDAO = SQLSellerDAOFactory.getDAO();

        boolean existsClient = sellerDAO.exists(connection, sellerVO.getIdVendedor());

        if (existsClient) {
            throw new UserNameAlreadyExistsException();
        } else {
            boolean existsNif = sellerDAO.existsNifCif(connection, sellerVO.getNifCif());
            if (existsNif) {

                throw new NifCifAlreadyExistsException();
            } else {
                return sellerDAO.create(connection, sellerVO);
            }
        }

    }
}
